<template>
  <div class="login-container123"
       style="display: flex;justify-content: center;
  padding-right: 20px;
  ">

    <!--  钉钉二维码-->
    <div style="margin-right: 20px;">
      <iframe src="/html/dingdinglogin.html"
              frameborder="no"
              scrolling="auto"
              allowtransparency
              height="353px"
              width="331px"
      ></iframe>
    </div>

    <div style="width: 280px;padding-top: 48px;padding-right: 50px;">
      <el-form
        ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on"
        label-position="left">


        <el-form-item prop="username">
          <div style="position: relative;display: flex;">
                <span style="margin-right: 15px;">
                <svg-icon icon-class="user" />
                 </span>
            <el-input
              style="width:100%;"
              ref="username"
              v-model="loginForm.username"
              placeholder="请输入登录账号"
              name="username"
              type="text"
              tabindex="1"
              autocomplete="on"
            />
          </div>
        </el-form-item>

        <el-form-item prop="password" style="margin-top: 20px;">
          <div style="display: flex;">
                <span class="svg-container" style="margin-right: 15px;">
                  <svg-icon icon-class="password" />
                </span>
            <div style="width: 100%;position: relative;">
              <el-input

                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入登录密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd" style="position: absolute;right: 10px;z-index:998;top: 50%; transform: translateY(-50%);">
            <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
          </span>
            </div>

          </div>
        </el-form-item>

        <el-form-item prop="submitbutton" style="margin-top: 40px;">

          <el-button type="primary" @click="submitByDialog" style="width: 233px;">登录</el-button>
        </el-form-item>


      </el-form>
    </div>
  </div>
</template>
<script>
import { validatePromise } from '@/utils/common'
import { dateFormatYYYYMMDDHHmmss, deepClone } from '@/utils'
import { dingdingCodeGOTO, login } from '@/api/login'
import { alertFail, alertSuccess } from '@/utils/alertUtil'
import { set_SINGLE_403_ALERT, setRefreshToken, setToken, setTokenUpdatedTime } from '@/utils/auth'
import { getPlatmentId } from '@/utils/dic/dingdingDic'

export default {
  data() {
    const validateUsername = (rule, value, callback) => {
      if (!value) {
        callback(new Error('登录账号不能为空'))
      } else {
        callback()
      }
    }
    const validatePassword = (rule, value, callback) => {
      if (value.length < 6) {
        callback(new Error('登录密码不能为空'))
      } else {
        callback()
      }
    }

    return {
      dialogCom: undefined,
      passwordType: 'password',
      capsTooltip: false,
      loading: false,
      loginRules: {
        username: [{ required: true, trigger: 'blur', validator: validateUsername }],
        password: [{ required: true, trigger: 'blur', validator: validatePassword }]
      },
      loginForm: {
        username: '',
        password: ''
      }
    }
  },
  methods: {
    destroyed() {
      var self = this
      window.removeEventListener('message', self.handleMessage, false)
    },

    checkCapslock(e) {
      const { key } = e
      this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
    },
    showPwd() {
      if (this.passwordType === 'password') {
        this.passwordType = ''
      } else {
        this.passwordType = 'password'
      }
      this.$nextTick(() => {
        this.$refs.password.focus()
      })
    },
    async ajaxDingdingCodeGoto() {
      var platmentId = getPlatmentId()
      var gotoyurl = await dingdingCodeGOTO(platmentId).then(res => res.data)
      return encodeURIComponent(gotoyurl + location.origin)

    },

    async initByDialog(_data) {
      this.dialogCom = _data?.dialogCom

      this.addListenerEvent()

    },
    handleMessage(event) {
      var self = this
      var loginResult = event.data
      console.log('-> [handleMessage] loginResult', loginResult)
      if (/*登录成功*/loginResult && loginResult.action == 'login_success') {
        var _data = loginResult && loginResult.data
        console.log('-> 获取得到的的  handleMessage about loginsuccess _data', _data)
        if (_data && _data.success) {
          alertSuccess('登录成功')
          self.dialogCom && self.dialogCom.closeDialog({ success: true })
        }
      }
    },

    addListenerEvent() {
      var self = this

      window.removeEventListener('message', self.handleMessage, false)
      window.addEventListener('message', self.handleMessage, false)

    },
    async submitByDialog() {
      var self = this
      //validate
      var isvalidate = await validatePromise.call(this, 'loginForm')
      if (!isvalidate) {
        return false
      }
      //data operation
      var userInfo = deepClone(this.loginForm)
      const username = userInfo.username.trim()
      const password = userInfo.password
      const code = userInfo.code
      const uuid = userInfo.uuid
      var result2 = await login(username, password, code, uuid)
      if (!(result2 && result2.success)) {
        alertFail(result2?.message)
        return false
      }
      //处理token
      var tokenInfo = result2?.data
      setToken(tokenInfo.accessToken)
      setRefreshToken(tokenInfo?.refreshToken)
      setTokenUpdatedTime(dateFormatYYYYMMDDHHmmss(tokenInfo?.refreshTime))
      set_SINGLE_403_ALERT('')
      alertSuccess('登录成功');

      setTimeout(() => {
        //初始化菜单
        window._vm.$store?.dispatch('GetMenus').then((accessRoutes) => {
          console.log('初始化一级菜单', accessRoutes)
        })

      }, 100)

      //ajax 提交

      this.dialogCom?.closeDialog(result2)
      return result2
    }
  }
}
</script>
